﻿using BS.Domain.RBAC;
using BS.Infra.Interface;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BS.Infra.Repository
{
    public class UserRepository : BaseRepository<UserInfo>,IUserRepository
    {
        private readonly ILogger<BaseRepository<UserInfo>> _logger;

        private readonly BaseDbContext _dbContext;
        public UserRepository(BaseDbContext dbContext, ILogger<BaseRepository<UserInfo>> logger) : base(dbContext, logger)
        {
            _dbContext = dbContext;
            _logger = logger;
        }

        public async Task<bool> InsertUserWithRole(UserInfo userInfo,int[] role)
        {
            bool result = false;
            using (var transaction = _dbContext.Database.BeginTransaction())
            {
                try
                {
                    //新增用户
                    var userapi = await _dbContext.UserInfo.AddAsync(userInfo);
                    await _dbContext.SaveChangesAsync();
                    //新增角色关联
                    foreach (var item in role)
                    {
                        await _dbContext.UserRole.AddAsync(new UserRole
                        {
                            UserId = userapi.Entity.UserId,
                            RoleId = item
                        });
                    }
                    //提交事务
                    await _dbContext.SaveChangesAsync();
                    await transaction.CommitAsync();
                    result = true;
                    
                }
                catch (Exception ex)
                {
                    await transaction.RollbackAsync();
                    _logger.LogError(ex, "InsertUserWithRole");
                    
                }
            }
            return result;
        }            
    }
}
